<template>
    <div class="order-layout">

        <!-- 贴顶导航 -->
        <UserFixedHead title="Orders" />

        <!-- 初始化加载中 -->
        <UxIniting v-if="!inited" />

        <!-- 空数据 -->
        <div class="order-nodata" v-else-if="empty">

            <h2>Orders</h2>
            <h3>Here you can manage all store orders and sample orders</h3>

            <ul>
                <li>
                    <figure><img src="@/assets/images/order/order-nodata-import.png" alt=""></figure>
                    <p>Your retail orders will be automatically imported to PODpartner</p>
                </li>
                <li>
                    <figure><img src="@/assets/images/order/order-nodata-bulk.png" alt=""></figure>
                    <p>Highly efficient order pocessing with Bulk & automatic payment options</p>
                </li>
            </ul>

            <h3>Place a sample order to test our product quality and see how your design looks in real life</h3>

            <blockquote>
                <figure><img src="@/assets/images/order/order-nodata-order.png" alt=""></figure>
                <p>
                    <span>100% cotton fabric</span>
                    <span>Excellent print quality</span>
                    <span>Rapid fulfillment</span>
                    <button type="primary" @click="!loading && beforeMakeOrder()">
                        <img src="@/assets/images/template/template-add.png" alt="">
                        <em>New order</em>
                        <UxLoading :loading="loading" size="24px" />
                    </button>
                </p>
            </blockquote>

        </div>

        <!-- 内容区 -->
        <template v-else>
            <h2>Orders</h2>
            <!-- 搜索 -->
            <div class="order-form">

                <UserSearchName v-model="form.order_code" size="large" shape="plain" placeholder="Orders ID"
                                @change="doSearch()" />

                <UserSearchStore v-model="form.shop_id" placeholder="Source" @change="doSearch()" />

                <UxDatepicker :start.sync="form.time_s" :end.sync="form.time_e" @change="doSearch()"
                              placeholder="Date" />

                <UserSearchButton shape="solid" name="New order" icon="user-template-new" @click="maker = {}" />

                <OrderBulkpay @update="reload()" />

            </div>

            <!-- 状态 -->
            <OrderTabs v-model="form.order_state" :counts="counts" @update="stateUpdate()" />

            <div class="order-match" v-show="searching">
                <span v-text="form.page_total"></span>
                <em v-if="form.page_total > 1"> matches found</em>
                <em v-else> match found</em>
            </div>


            <!-- 表头 -->
            <div class="order-table-title">
                <span>Order ID</span>
                <span>Source</span>
                <span>Recipient</span>
                <span>Date</span>
                <span>Total</span>
                <span>Status</span>
            </div>

            <UxSearchEmpty v-if="table.length == 0" />

            <div class="order-table" v-else>
                <ul>
                    <li v-for="item in table" :key="item.order_code" @click="showDetail(item)">
                        <div class="table-code" v-text="item.order_code"></div>
                        <div class="table-shop">
                            <StoreIconOrder :item="item" />
                        </div>
                        <div class="table-recipient">
                            <span v-text="item.first_name" :title="item.first_name"></span>
                            <img src="@/assets/images/order/order-remote-sign.png" v-if="item.remote_sign">
                        </div>

                        <div class="table-time" v-text="getCreatedDate(item.created_at)"></div>
                        <div class="table-price">
                            <CommonCurrencyRate :price="item.total_money" :cover="item" />
                        </div>
                        <div class="table-status">
                            <OrderState :info="item" />
                        </div>
                    </li>
                </ul>
                <CommonPage v-show="form.page_total > form.page_size" @current-change="pageUpdate($event)"
                            :current-page.sync="form.page_num" :page-size="form.page_size"
                            :total.sync="form.page_total"></CommonPage>
            </div>

            <UxLoading2 class="order-loading" :loading="loading" />

        </template>

        <!-- 详情弹窗 -->
        <OrderDetail v-model="detail" @reload="reload()" />

        <!-- 选择图片弹窗 -->
        <!-- 下单选择订单类型 -->
        <UserMakeOrder v-model="maker" />
    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";

export default {
    name: "orderList",
    layout: "layout-user",
    data () {
        return {
            empty: true,
            inited: false,
            loading: false,
            searching: false,
            form: {
                order_code: "",
                page_num: 1,
                page_size: 10,
                page_total: 0,
                shop_id: "",
                time_s: 0,
                time_e: 0,
                order_state: "0",
            },
            table: [],
            counts: null,
            maker: null,
            detail: null,
            bulkpay: false,
        };
    },
    computed: {
        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),

    },
    watch: {
        currency () {
            this.loading = true;
            this.getData().then(() => this.loading = false)
        }
    },
    methods: {

        // 类型统计
        async getTabs (force) {
            let request = {
                order_code: (this.form.order_code || '').trim(),
                shop_id: this.form.shop_id,
                time_s: this.form.time_s,
                time_e: this.form.time_e,
            };

            let response = await this.$http("Order.getOrderCount", request);
            let data = response.data || {};
            if (response.code == 0) {
                this.counts = data;
            }
        },

        //请求函数
        async getData () {
            this.loading = true;

            const request = {
                order_code: (this.form.order_code || '').trim(),
                page_num: this.form.page_num,
                page_size: this.form.page_size,
                shop_id: this.form.shop_id,
                time_s: this.form.time_s,
                time_e: this.form.time_e,
                currency: this.currency,
                order_state: Number(this.form.order_state),
            };
            const response = await this.$http("Order.getOrderList", request);

            if (response.code == 0) {

                const list = response.data.OrderList || [];

                list.map(item => item.loading = item.order_state == 2 && item.order_pay_state == 1)

                this.table = list;
                this.loading = false;
                this.form.page_total = response.total;
                this.searching = request.order_code || request.shop_id || request.time_s || request.time_e;
                this.getOrderStatus();
            } else {
                this.loading = false;
                this.$uxMessage.warning(response.msg || "Failed to load orders");
            }
        },

        // 创建订单前查询模板
        async beforeMakeOrder () {
            if (this.loading) return;
            let request = {
                page_num: 1,
                page_size: 1,
            };
            this.loading = true;
            let response = await this.$http("storeTemplate.getList", request);
            if (response.code === 0) {
                if (response.total > 0) {
                    this.maker = {};
                } else {
                    //打开商品列表弹窗
                    this.$emit("global:productDialogOpen");
                }
                // 跳转
            } else {
                this.$uxMessage.error("Failed to load templates");
                // 提示
            }
            this.loading = false;
        },

        // 获取时间工具函数
        getCreatedDate (date) {
            let time = new Date(date).getTime();
            return this.$timeFormat(time);
        },

        // 搜索
        doSearch () {
            this.form.page_num = 1;
            this.form.order_state = 0;
            this.loading = true;
            Promise.all([this.getData(), this.getTabs()]).then(() => {
                this.loading = false;
                window && window.scrollTo(0, 0)
            })
        },

        // 分页数据改变
        pageUpdate (value) {
            this.form.page_num = value;
            this.loading = true;
            this.getData().then(() => {
                this.loading = false
                window && window.scrollTo(0, 0)
            })
        },

        // 状态改变
        stateUpdate () {
            this.form.page_num = 1;
            this.loading = true;
            this.getData().then(() => {
                this.loading = false
                window && window.scrollTo(0, 0)
            })
        },

        // 刷新当前页
        reload (keys) {
            this.loading = true;
            Promise.all([this.getData(), this.getTabs()]).then(() => this.loading = false)
        },

        // 查看详情
        showDetail (row) {
            this.detail = row;
        },

        // 获取状态
        getOrderStatus () {

            let pending = this.table.filter((i) => i.order_state == 2 && i.order_pay_state == 1);
            let pendobj = Object.fromEntries(pending.map((i) => [i.order_code, i]));
            let codes = pending.map((i) => i.order_code);

            codes.length > 0 && this.$http("Order.getOrderStatus", { order_codes: codes }).then(response => {

                (response.data || []).map((item) => {

                    let status = pendobj[item.order_code];
                    if (!item || !status) {
                        // 为空不管他
                    } else if (item.order_state == status.order_state && item.order_pay_state == status.order_pay_state) {
                        // 状态相同，不管他
                    } else {
                        // 支付状态变更
                        const stateChange = item.order_state != status.order_state;

                        status.order_state = item.order_state;
                        status.order_pay_state = item.order_pay_state;

                        // 状态改变
                        stateChange && this.getTabs(true);
                        status.loading = status.order_state == 2 && status.order_pay_state == 1 ? true : false;

                        if (status.order_state == 1) {
                            // 支付状态改为未支付
                        }else if (status.order_pay_state == 2) {
                            // delayed，延迟支付
                            // this.$uxMessage.success('');
                        } else if (status.order_pay_state == 10 || status.order_pay_state == 0) {
                            // complete，支付完成
                            this.$uxMessage.success('Order ' + status.order_code + ' paid completed！');
                        } else if (status.order_pay_state == 20) {
                            // failed，支付失败
                            // this.$uxMessage.success('');
                        }
                    }
                });

                this.polling && clearTimeout(this.polling);
                this.polling = setTimeout(this.getOrderStatus, 1000);
            })

        },

    },
    created () {

        if (process.client) {
            this.form.order_state = this.$route.query.order_state || 0;
            Promise.all([this.getTabs(true), this.getData()]).then(res => {
                this.inited = true;
                this.empty = this.counts.all_count == 0;
            })
            this.$on('global:ORDER_UPDATA_PRICE', this.getData);
        }
    },

    beforeDestroy () {
        this.polling && clearTimeout(this.polling);
    },
};
</script>
<style lang="scss" scoped>
.order-layout {
    position: relative;
    display: flex;
    flex-direction: column;

    &>h2 {
        height: 40px;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
    }

    .initing {
        flex: 1;
    }

    &>.order-loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
        opacity: 0;
        pointer-events: none;
        transition: all 0.5s;

        &.active {
            opacity: 1;
            pointer-events: all;
        }
    }

    .search-empty {
        margin-top: 12px;
    }
}

.order-nodata {
    flex: 1;

    &>h2 {
        height: 40px;
        font-size: 36px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
        margin-bottom: 24px;
    }

    &>h3 {
        font-size: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 22px;
        margin-bottom: 18px;
    }

    ul {
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        padding: 28px 20px;
        display: flex;
        margin-bottom: 40px;

        li {
            width: calc(50% - 16px);
            margin: 0 8px;
        }

        figure {
            position: relative;
            background: #f8f8f8;
            border-radius: 6px;

            &::before {
                content: '';
                display: block;
                padding-bottom: 51.59%;
            }

            img {
                position: absolute;
                left: 50%;
                height: 100%;
                top: 0;
                transform: translateX(-50%);
            }
        }

        p {
            margin-top: 20px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;
            line-height: 16px;
        }
    }

    blockquote {
        display: flex;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        padding: 28px;
        margin: 0;
        align-items: center;

        figure {
            flex: 700;
            position: relative;

            &::before {
                content: '';
                display: block;
                padding-bottom: 40.86%;
            }

            img {
                position: absolute;
                left: 50%;
                height: 100%;
                top: 0;
                transform: translateX(-50%);
            }
        }

        p {
            flex: 212;
            padding: 0 44px;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin-left: 24px;

            span {
                font-size: 16px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000;
                line-height: 24px;
                padding-left: 20px;
                position: relative;

                &::before {
                    content: '';
                    position: absolute;
                    left: 0;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 5px;
                    height: 5px;
                    border-radius: 5px;
                    background-color: #555;
                }

                &+span {
                    margin-top: 8px;
                }
            }

            button {
                margin-top: 24px;
                width: 144px;
                height: 40px;
                border-radius: 8px;
                font-size: 14px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;

                img {
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                }

                .loading-inline::v-deep svg {
                    width: 32px;
                    height: 32px;
                }
            }
        }
    }
}

.order-form {
    margin-top: 40px;
    margin-bottom: 40px;
    position: relative;
    display: flex;

    .user-search-name {
        flex: 320;
    }

    .user-search-store {
        flex: 200;
        width: 200px;
        margin-left: 6px;
    }

    .mx-datepicker {
        flex: 200;
        width: 200px;
        min-width: initial;
        margin-left: 6px;
    }

    .user-search-button {
        margin-left: 52px;
        min-width: 144px;
    }

    .bulkpay {
        margin-left: 6px;
    }
}

.order-tabs {
    margin-bottom: 28px;
}

.order-match {
    margin-top: 12px;
    margin-bottom: 20px;
    font-size: 22px;
    font-family: Roboto-Medium, Roboto;
    font-weight: 500;
    color: #000000;
    line-height: 22px;
}

.order-table-title>span,
.order-table li>div {
    &:nth-child(1) {
        width: 20%;
    }

    &:nth-child(2) {
        width: 16%;
    }

    &:nth-child(3) {
        width: 18%;
    }

    &:nth-child(4) {
        width: 18%;
    }

    &:nth-child(5) {
        width: 14%;
    }

    &:nth-child(6) {
        width: 14%;
    }
}

.order-table-title {
    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    display: flex;

    span {
        padding: 10px 18px;
        box-sizing: border-box;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #292929;
        line-height: 20px;
    }
}

.order-table {
    li {
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        margin-top: 12px;
        position: relative;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
            box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.1);
        }

        &>div {
            box-sizing: border-box;
            padding: 14px 18px;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
        }

        &>.table-code {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }

        &>.table-shop {}

        &>.table-recipient {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: flex;
            align-items: center;

            span {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            img {
                width: 20px;
                height: 20px;
                margin-left: 4px;
            }
        }

        &>.table-time {
            // text-align: center;
        }

        &>.table-price {
            display: flex;

            .currency-rate {
                line-height: 24px;
                font-size: 14px;
                color: #000000;
                font-weight: normal;
                white-space: nowrap;

                img {
                    height: 24px;
                    margin-right: 4px;
                }
            }
        }

        &>.table-status {
            .order-name {
                height: 24px;
                padding-left: 18px;
                position: relative;
                max-width: 100%;
                box-sizing: border-box;

                &::before {
                    content: '█';
                    position: absolute;
                    left: 10px;
                    top: 50%;
                    width: 4px;
                    height: 4px;
                    margin-top: -2px;
                    border-radius: 4px;
                    overflow: hidden;
                    line-height: 0px;
                    font-size: 100px;
                    text-align: center;
                }

                &::v-deep span {
                    font-size: 12px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                &::v-deep svg {
                    display: none;
                }
            }
        }
    }
}

.display-none {
    display: none;
}

.bulkpay {
    margin-left: auto;
}

.order-body {
    flex: 1;
    display: flex;
    flex-direction: column;
}

// .order-nodata {
//     margin-top: 20px;
//     font-size: 24px;
//     i {
//         font-size: 72px;
//     }
// }

/*
.order-table {
    margin-top: 20px;
    position: relative;
    flex: 1;
    border-radius: 8px;
    background: #fff;
    box-sizing: border-box;
    padding: 16px;
    display: flex;
    flex-direction: column;

    &::v-deep .el-loading-mask {
        border-radius: 8px;
        z-index: 9;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        thead {
            height: 36px;
            line-height: 36px;
            font-size: 14px;

            color: #000000;
            white-space: nowrap;
            th {
                position: relative;
                background: #f0f0f0;
                text-align: center;
                font-weight: normal;
                padding: 0;
                font-weight: bold;
                &::before {
                    content: '';
                    display: block;
                    position: absolute;
                    width: 1px;
                    height: 22px;
                    background: #d8d8d8;
                    right: 0;
                    top: 50%;
                    transform: translateY(-50%);
                }
                &:first-child {
                    border-radius: 2px 0 0 2px;
                }
                &:last-child {
                    border-radius: 0 2px 2px 0;
                    &::before {
                        display: none;
                    }
                }
            }
        }
        tbody {
            tr:nth-child(2n) {
                td {
                    background: #fafafa;
                }
            }
            tr:hover {
                td {
                    background: #eeeeee;
                }
            }
            td {
                padding: 26px;
                text-align: center;
                cursor: pointer;
                transition: background 0.5s;
                &::v-deep .shop-name {
                    figure {
                        width: 24px;
                        height: 24px;
                        margin-right: 4px;
                    }
                    span {
                        line-height: 24px;
                        font-size: 14px;

                        color: #000000;
                        font-weight: normal;
                        white-space: nowrap;
                    }
                }
                &.table-shop {
                    box-sizing: border-box;
                    min-width: 150px;
                }
                &.table-recipient {
                    p {
                        overflow: hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-line-clamp: 3;
                        -webkit-box-orient: vertical;
                        /*height: 100%;*
                    }
                }
                .currency-rate,
                p {
                    line-height: 24px;
                    font-size: 14px;

                    color: #000000;
                    font-weight: normal;
                    white-space: nowrap;

                    img {
                        height: 24px;
                        margin-right: 4px;
                    }
                }
            }
        }

        .table-shop p {
            white-space: pre-wrap;
            word-break: break-word;
        }

        .table-recipient p {
            white-space: pre-wrap;
            word-break: break-word;
        }

        .order-name ::v-deep {
            i {
                display: none;
            }
            b {
                line-height: 24px;
                font-size: 14px;
                font-weight: normal;
            }
        }
    }


    hr {
        width: calc(100% + 32px);
        transform: translateX(-16px);
        margin-top: 78px;
        border: none;
        height: 1px;
        background-color: #dcdcdc;
    }

    .search-empty {
        flex: 1;
        height: 100%;
        justify-content: center;
    }
}

*/

.common-page {
    padding: 24px 0 0;
    justify-content: flex-end;
}

// v-if="tableCount.testing_ok_count"
// name="6"
// v-if="tableCount.canceled_count"
// name="11"
// v-if="tableCount.completed_count"
// name="10"</style>
